package com.travel.mapper.content;

import com.travel.model.entity.content.Comment;
import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Optional;
//评论mapper 查询评论 插入评论 更新评论 删除评论 获取评论平均评分 获取评论数量  
@Mapper
public interface CommentMapper {
    
    @Select("SELECT * FROM comments WHERE id = #{id}")
    Optional<Comment> findById(@Param("id") Long id);
    
    @Select("SELECT c.*, " +
            "u.nickname as user_nickname, " +
            "u.avatar as user_avatar, " +
            "u.status as user_status " +
            "FROM comments c " +
            "LEFT JOIN users u ON c.user_id = u.id " +
            "WHERE c.target_id = #{targetId} " +
            "AND c.target_type = #{targetType} " +
            "AND c.status = #{status}")
    @Results({
        @Result(property = "id", column = "id"),
        @Result(property = "content", column = "content"),
        @Result(property = "userId", column = "user_id"),
        @Result(property = "targetId", column = "target_id"),
        @Result(property = "targetType", column = "target_type"),
        @Result(property = "rating", column = "rating"),
        @Result(property = "status", column = "status"),
        @Result(property = "createdTime", column = "created_time"),
        @Result(property = "updatedTime", column = "updated_time"),
        @Result(property = "user.id", column = "user_id"),
        @Result(property = "user.nickname", column = "user_nickname"),
        @Result(property = "user.avatar", column = "user_avatar"),
        @Result(property = "user.status", column = "user_status")
    })
    List<Comment> findByTargetAndStatus(
        @Param("targetId") Long targetId, 
        @Param("targetType") Comment.TargetType targetType,
        @Param("status") Integer status
    );
    
    @Insert("INSERT INTO comments (content, user_id, target_id, target_type, rating, status, created_time) " +
            "VALUES (#{content}, #{userId}, #{targetId}, #{targetType}, #{rating}, #{status}, #{createdTime})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(Comment comment);
    
    @Update("UPDATE comments SET status = #{status}, updated_time = #{updatedTime} WHERE id = #{id}")
    void update(Comment comment);
    
    @Delete("DELETE FROM comments WHERE id = #{id}")
    int delete(@Param("id") Long id);
    
    @Select("SELECT AVG(rating) FROM comments " +
            "WHERE target_id = #{targetId} AND target_type = #{targetType} AND status = 1")
    Double getAverageRating(@Param("targetId") Long targetId, 
                           @Param("targetType") Comment.TargetType targetType);
    
    @Select("SELECT COUNT(*) FROM comments " +
            "WHERE target_id = #{targetId} AND target_type = #{targetType} AND status = 1")
    Integer getCommentCount(@Param("targetId") Long targetId, 
                          @Param("targetType") Comment.TargetType targetType);
} 